package com.brush.framework.security.filter;

import com.brush.common.core.domain.resp.AppUserDetails;
import com.brush.framework.web.service.AppTokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * app自定义过滤器
 * @author tonneyyy
 */
@Log4j2
@Component
public class AppAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AppTokenService appTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 根据请求头，获取令牌，查询redis中是否存在数据
        AppUserDetails loginUser = this.appTokenService.getLoginUser(request);
        System.out.println(request.getRequestURL());
       if(Objects.nonNull(loginUser)){
           //增加一个令牌续时的功能
           this.appTokenService.verifyToken(loginUser);

           // spring security 框架提供的方法，设置用户信息

           //自己已经确认过，系统放心接收
           UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
           authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

           SecurityContextHolder.getContext().setAuthentication(authenticationToken);
       }

       //放行,继续执行下一个过滤器
        filterChain.doFilter(request, response);
    }
}
